const BaseRest = require('../rest.js');
module.exports = class extends BaseRest
{
    constructor(ctx)
    {
        super(ctx);
        this._model = this.model('apiv1/application');
        this.workModel = this.model('apiv1/works');
        this.cpModel = this.model('apiv1/competition');
        this.stModel = this.model('apiv1/competitionSteps');
        this.gradeModel = this.model('apiv1/grade');
        this.cpstepToWorkModel = this.model('apiv1/competitionsteptoworks');
        this.judgerModel = think.model('apiv1/judger');
        this.appModel = think.model('apiv1/application');
    }

    /**
     * 更新作品
     * @returns {Promise.<*>}
     */
    async updateWorkAction()
    {

        //作品表数据
        let data = this.ctx.state.updateWorkData;
        let wkguid = this.ctx.state.updateWorkData.wkguid;
        data.IsDelete = '未删除';
        data.UpdateTime = think.nowTimestamp();
        let res = await this.workModel.where({PK_WorksGuid: wkguid}).update(data);
        return this.infoDbUpdate(res);

    }

    /**
     * 作品详情
     * @returns {Promise.<*>}
     */
    async getAction()
    {
        let data;
        if (this._guid)
        {
            const pk = this.modelInstance.pk;
            data = await this.modelInstance.where({[pk]: this._guid, IsDelete: '未删除'}).find();
            if (think.isEmpty(data)) return this.end();
            let stepguid = data.competitionsteptoworks.FK_CompetitionStepsGuid;
            if (think.isEmpty(stepguid)) return this.end();
            let cpguid = (await this.model('apiv1/competitionSteps').where({PK_CompetitionStepsGuid: stepguid}).getField('FK_CompetitionGuid'))[0];
            let cptype = (await this.model('apiv1/competition').where({PK_CompetitionGuid: cpguid}).getField('ApplyType'))[0];
            let appInfo = await this.model('apiv1/application').where({FK_CompetitionGuid: cpguid}).find();
            data.application = appInfo;
            data.applyType = cptype;
            return this.end(data);
        }
        // data = await this.modelInstance.select();
        return this.end();
    }

    /**
     * 获取用户的所有作品
     * @returns {Promise.<*>}
     */
    async getUserWorksByUserGuidAction()
    {
        let usrGuid = this._guid;
        let worksData = await this.model('apiv1/works').where({FK_UserGuid: usrGuid, IsDelete: '未删除'}).select()
        return this.end(worksData);
    }

    /**
     * 删除作品
     * @returns {Promise.<*>}
     */
    async deleteAction()
    {
        if (!this._guid)
        {
            return this.error(52015, '删除数据时guid不能为空,请检查参数')
        }
        let res = await this.model('apiv1/works').where({'PK_WorksGuid': this._guid}).update({'IsDelete': "已删除"});

        if (res === 1)
        {
            return this.error(0, "删除成功");
        } else
        {
            return this.error(52016, "该比赛不存在,请检查guid");
        }
    }

    /**
     * 根据比赛流程获取所有作品
     */
    async getWorksByStepGuidAction()
    {
        this.workNoModel = this.model('apiv1/competitionsteptoworks');
        return this.end(await this.workNoModel.getWorksByStepGuid(this._guid));
    }


    /**
     * 上传作品
     * @returns {Promise.<void>}
     */
    async uploadWorkAction()
    {
        let work_step_data = {};

        //作品表数据
        let data = this.ctx.state.uploadWorkData;
        data.PK_WorksGuid = think.uuid('v3');
        data.PK_CompetitionStepsGuid = data.stepguid;
        data.FK_UserGuid = data.userguid;
        data.IsDelete = '未删除';
        data.CreateTime = think.nowTimestamp();

        //中间表数据
        work_step_data.PK_WorksNoGuid = think.uuid('v3');
        work_step_data.FK_WorksGuid = data.PK_WorksGuid;
        work_step_data.FK_CompetitionStepsGuid = data.PK_CompetitionStepsGuid;


        let stepguid = data.stepguid;
        let userguid = data.userguid;
        let cpguid = (await  this.stModel.find(stepguid))['FK_CompetitionGuid'];
        if (!cpguid) return this.responseInfo(20003);
        let applicationInfo = await this.appModel.where({FK_CompetitionGuid: cpguid, FK_UserGuid: userguid}).find();
        if (think.isEmpty(applicationInfo)) return this.responseErrmsg('请补充完整参赛信息后重试');
        data.Auther = applicationInfo['TeamName'] ? applicationInfo['TeamName'] : applicationInfo['Name'];
        let addInfo = await this._model.addWorks(data, work_step_data);
        this.error(addInfo);
    }


    async getUserCourrentCompetitionStepWorksAction()
    {
        let guidRule = {
            stguid: {type: 'string', min: 5, max: 36},
            usrguid: {type: "string", min: 5, max: 36}

        };
        let vres = think.validate(this.get(), guidRule);
        if (vres !== true)
        {
            let errmsg = '';
            vres.forEach(function (obj, index)
            {
                errmsg += "第" + (index + 1) + "个错误:" + obj.message;
            })
            return this.infoFastValidate(errmsg);
        }

        let stguid = this.get('stguid');
        let usrguid = this.get('usrguid');
        let nowStepWorks = await this.model('apiv1/competitionsteptoworks').getWorksByStepGuid(stguid);
        if (think.isEmpty(nowStepWorks))
        {
            return this.responseEmpty();
        }
        let responseData = [];
        nowStepWorks.forEach(function (obj)
        {
            if (obj.works.FK_UserGuid === usrguid)
            {
                responseData.push(obj);
            }
        });
        this.responseQuery(responseData);

    }


    async userCurrentCompetitionWorksAction()
    {
        let cpguid = this.get('cpguid');
        let usrguid = this.get('usrguid');
        //获取流程的guid
        let stepsData = await this.stModel.getCPStepsByCPGuid(cpguid);
        if (think.isEmpty(stepsData))
        {
            return this.responseEmpty();
        }
        let worksGuids = [];
        stepsData.forEach(function (obj)
        {
            let works = obj.competitionsteptoworks;
            if (think.isEmpty(works)) return;
            works.forEach(function (obj)
            {
                let workguid = obj.FK_WorksGuid;
                if (workguid.length > 10)
                {
                    worksGuids.push(workguid);
                }
            })

        })
        if (think.isEmpty(worksGuids)) return this.responseEmpty();
        let worksData = await this.workModel.select({
            where: {PK_WorksGuid: ['in', worksGuids],IsDelete:'未删除'}
        });
        return this.responseQuery(worksData);
    }


    //打分
    async doGradeAction()
    {
        let postData = think.stringToJson(this.post('data'));
        if (postData === false)
        {
            return this.fail(52004, '提交的表单信息错误,该数据必须为json格式,请检查数据格式,上传数据格式为{\'data\',yourJsonData},如 : $.post("http://127.0.0.1:8091/apiv1/competition",{\'data\':yourJsonData}),yourJsonData为你要上传的数据包');
        }
        //获取作品的序号
        // let workNoGuid = await  this.cpstepToWorkModel.where({
        //     FK_WorksGuid: postData['wkguid']
        // }).getField('PK_WorksNoGuid', true);
        let workNoGuid = await  this.cpstepToWorkModel.getWornNoByWkguid(postData['wkguid']);

        //检查作品
        if (think.isEmpty(workNoGuid)) return this.responseInfo(20000);


        //检查评委
        let isJudger = await this.judgerModel.find(postData['jrguid']);
        if (think.isEmpty(isJudger)) return this.responseInfo(20001);

        let res = await  this.gradeModel.add({
            PK_GradeGuid: think.uuid('v3'),
            FK_WorksNoGuid: workNoGuid,
            FK_JudgerGuid: postData['jrguid'],
            Grade: postData['grade']
        });

        return this.responseAdd(res);

    }

    async getGradeAction()
    {
        let wkguid = this.get('wkguid');
        if (think.isEmpty(wkguid)) return this.responseErrmsg('wkguid不能为空');
        let workNoGuid = await  this.cpstepToWorkModel.getWornNoByWkguid(wkguid);
        //检查作品
        if (think.isEmpty(workNoGuid)) return this.responseInfo(20000);

        let jrguid=this.get("jrguid");
        if (think.isEmpty(jrguid)) return this.responseErrmsg('wkguid不能为空');
        return this.responseQuery(
            await this.gradeModel.where({
                FK_WorksNoGuid: workNoGuid,
                FK_JudgerGuid: jrguid
            }).find()
        );
    }


};